/* ContactListActivity.java
 *
 * Copyright 2011-2012 r.u.s.h.a.n.
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import org.jimm.protocol.AccountsManager;
import org.jimm.protocol.Contact;
import org.jimm.protocol.ContactMenu;
import org.jimm.protocol.Group;
import org.jimm.protocol.Protocol;
import org.jimm.protocol.StatusInfo;
import org.jimm.protocol.TreeNode;
import org.jimm.protocol.XStatusInfo;
import org.jimm.service.Preferences;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Spinner;

/**
 * @author r.u.s.h.a.n.
 */
public class ContactListActivity extends JimmActivity {
    private static final String LOG_TAG = "Jimm:ContactListActivity";

    private ContactListAdapter contactListAdapter;
    private Preferences p = JimmApplication.getInstance().getPreferences();

    //    private static final int MENU_CONNECT = 1;
//    private static final int MENU_DISCONNECT = 2;
//    private static final int MENU_STATUS = 3;
    private static final int MENU_ADD_CONTACT = 5;
    //    private static final int MENU_MYSELF = 6;
//    private static final int MENU_MAGIC_EYE = 8;
    private static final int MENU_ABOUT = 9;
    private static final int MENU_QUIT = 10;

    public void openChat(Contact contact) {
        try {
            contactListAdapter.update();
            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra(ChatActivity.CONTACT_ID_EXTRA, contact.getUserId());
            intent.putExtra(ChatActivity.ACCOUNT_ID_EXTRA, contact.getProtocol().getUserId());
            intent.putExtra(ChatActivity.MSG_TEXT_EXTRA, "");
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(LOG_TAG, "onCreate()");
        super.onCreate_(savedInstanceState);

        setContentView(R.layout.contact_list);
        
        contactListAdapter = new ContactListAdapter(this);
        ListView contactList = (ListView) findViewById(R.id.contacts);
        contactList.setAdapter(contactListAdapter);
        contactList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {

            	TreeNode node = contactListAdapter.getItem(arg2);

                if (node instanceof Protocol) {
                    ((Protocol) node).setExpandFlag(!((Protocol) node).isExpanded());
                    //contactListAdapter.update();
                    contactListAdapter.buildContactList();
                    contactListAdapter.notifyDataSetChanged();
                } else if (node instanceof Group) {
                    ((Group) node).setExpandFlag(!((Group) node).isExpanded());
                    contactListAdapter.buildContactList();
                    contactListAdapter.notifyDataSetChanged();
                } else if (node instanceof Contact) {
                    openChat((Contact) node);
                }
            }
        });
        contactList.setOnCreateContextMenuListener(this);

        final ImageView imageOnline = (ImageView) findViewById(R.id.panel_cl_mode);
        final ImageView imageSound = (ImageView) findViewById(R.id.panel_sound_mode);
        final ImageView imageOptions = (ImageView) findViewById(R.id.panel_options);
        final ImageView imageStatus = (ImageView) findViewById(R.id.status_button);
        final ImageView imageXStatus = (ImageView) findViewById(R.id.xstatus_button);
        final ImageView imagePrivateStatus = (ImageView) findViewById(R.id.private_status_button);

        imageOnline.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                p.hideOfflineContacts = !p.hideOfflineContacts;
                p.save();
                contactListAdapter.buildContactList();
                contactListAdapter.notifyDataSetChanged();

                invalidate();
                Log.i(LOG_TAG, "Preferences.hideOfflineContacts = " + p.hideOfflineContacts);
            }
        });

        imageSound.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                p.soundEnabled = !p.soundEnabled;
                p.save();
                Log.i(LOG_TAG, "Preferences.soundEnabled = " + p.soundEnabled);
                invalidate();
            }
        });

        imageOptions.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(ContactListActivity.this, OptionsActivity.class));
            }
        });
        /***********************************************************/
        final GridView protocolsGrid = (GridView) findViewById(R.id.protocols_grid);
        BaseAdapter protocolsAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return JimmApplication.getInstance().getAccountsManager().getCount();
            }

            @Override
            public Integer getItem(int position) {
                return JimmApplication.getInstance().getAccountsManager().getProtocol(position).getCurrentStatusIcon();
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                Log.i(LOG_TAG, "getView(position = " + position + "); ");
                if (convertView == null) {
                    convertView = new ImageView(getApplicationContext());
                    convertView.setLayoutParams(new GridView.LayoutParams(42, 42));
                }
                ImageView view = (ImageView) convertView;
                view.setImageResource(getItem(position));
                return view;
            }
        };
        protocolsGrid.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                Intent intent = new Intent(ContactListActivity.this, StatusActivity.class);
                intent.putExtra(StatusActivity.PROTOCOL_ID, String.valueOf(position));
                intent.putExtra(StatusActivity.TYPE, "status");
                startActivity(intent);
                //finish();
            }
        });
        protocolsGrid.setAdapter(protocolsAdapter);
        /***********************************************************/

        imageStatus.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(ContactListActivity.this, StatusActivity.class);
                intent.putExtra(StatusActivity.TYPE, "global_status");

                startActivity(intent);
            }
        });


        imageXStatus.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(ContactListActivity.this, XStatusActivity.class));
            }
        });

        imagePrivateStatus.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(ContactListActivity.this, StatusActivity.class);
                intent.putExtra(StatusActivity.TYPE, "private_status");

                startActivity(intent);
            }
        });

        //draw();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        //JimmApplication app = JimmApplication.getApplication();

        //if (app.getAccountsManager().isConnected())
        menu.add(Menu.FIRST, MENU_ADD_CONTACT, 0, R.string.add_contact).setIcon(android.R.drawable.ic_menu_add);

        menu.add(Menu.FIRST, MENU_ABOUT, 0, R.string.about).setIcon(android.R.drawable.ic_menu_info_details);
        menu.add(Menu.FIRST, MENU_QUIT, 0, R.string.quit).setIcon(android.R.drawable.ic_menu_close_clear_cancel);

        return true;
    }

    private AccountsManager am;
    private String protocolName;
    private String groupName;

    private String[] protocols;
    private String[] groups = {""};

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {

            case MENU_ADD_CONTACT: {
                am = JimmApplication.getInstance().getAccountsManager();

                protocols = am.getOnlineProtocolList();

                final Dialog dialogAddContact = new Dialog(this);
                dialogAddContact.setContentView(R.layout.contact_add);
                dialogAddContact.setTitle(R.string.add_contact);

                final EditText editLogin = (EditText) dialogAddContact.findViewById(R.id.add_contact_login_edit);
                final EditText editNick = (EditText) dialogAddContact.findViewById(R.id.add_contact_nick_edit);

                final Spinner selectAccountSpinner = (Spinner) dialogAddContact.findViewById(R.id.add_contact_account_spinner);
                final Spinner selectGroupSpinner = (Spinner) dialogAddContact.findViewById(R.id.add_contact_account_spinner);

                final ArrayAdapter<String> selectAccountAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, protocols);
                final ArrayAdapter<String> selectGroupAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, groups);

                selectAccountSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                        protocolName = protocols[position];
                        Protocol p = am.getProtocol(protocolName);

                        groups = p.getGroups();
                        selectGroupAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }

                });

                selectAccountAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                selectAccountSpinner.setAdapter(selectAccountAdapter);

                selectGroupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                        groupName = groups[position];
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }

                });

                selectGroupAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                selectGroupSpinner.setAdapter(selectGroupAdapter);

                Button buttonAdd = (Button) dialogAddContact.findViewById(R.id.add_button);
                buttonAdd.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Protocol p = am.getProtocol(protocolName);

                        Contact c = p.createContact(editLogin.getText().toString(), editNick.getText().toString());

                        c.setGroup(p.getGroup(groupName));

                        p.addContact(c);

                        dialogAddContact.dismiss();
                    }

                });
                dialogAddContact.show();
                break;
            }

            case MENU_ABOUT:
                startActivity(new Intent(this, AboutActivity.class));
                break;

            case MENU_QUIT:
                JimmApplication.getInstance().stopService(this);
                break;

            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

        super.onCreateContextMenu(menu, v, menuInfo);

        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;

       contactListAdapter.getItem(info.position).getContextMenu(menu, this);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

        TreeNode node = contactListAdapter.getItem(info.position);

        if (node instanceof Protocol) {
            //((ProtocolBranch)node).setExpandFlag(!((ProtocolBranch)node).isExpanded());
        } else if (node instanceof Group) {
            //((Group)node).setExpandFlag(!((Group)node).isExpanded());
        } else if (node instanceof Contact) {
            Contact c = (Contact) node;
            new ContactMenu(c.getProtocol(), c, this).doAction(item.getItemId());
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

        invalidate();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfiguration) {
        super.onConfigurationChanged(newConfiguration);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        contactListAdapter.uninitialize();
    }

    @Override
    public void invalidate() {
        Log.i(LOG_TAG, "invalidate()");
        runOnUiThread(new Runnable() {

            public void run() {
                draw();
            }
        });
        if (contactListAdapter != null)
            contactListAdapter.update();
    }

    public void draw() {

        if (p == null) return;

        Log.i(LOG_TAG, "draw()");

        final ImageView imageOnline = (ImageView) findViewById(R.id.panel_cl_mode);
        final ImageView imageSound = (ImageView) findViewById(R.id.panel_sound_mode);

        final GridView protocolsGrid = (GridView) findViewById(R.id.protocols_grid);
        final ImageView imageStatus = (ImageView) findViewById(R.id.status_button);
        final ImageView imageXStatus = (ImageView) findViewById(R.id.xstatus_button);
        final ImageView imagePrivateStatus = (ImageView) findViewById(R.id.private_status_button);

        if (p.hideOfflineContacts)
            imageOnline.setImageResource(R.drawable.ic_toggle_offline_a);
        else
            imageOnline.setImageResource(R.drawable.ic_toggle_offline);

        if (p.soundEnabled)
            imageSound.setImageResource(R.drawable.pannel_sound_turn_on);
        else
            imageSound.setImageResource(R.drawable.pannel_sound_turn_off);

        //protocolsAdapter.notifyDataSetChanged();
        // TODO Сделать обновление иконок,
        protocolsGrid.invalidate();

        if (JimmApplication.getInstance().getAccountsManager().isConnecting())
            imageStatus.setImageResource(StatusInfo.getGlobalStatusIcon(StatusInfo.STATUS_CONNECTING));
        else if (JimmApplication.getInstance().getAccountsManager().isConnected())
            imageStatus.setImageResource(StatusInfo.getGlobalStatusIcon(p.statusIndex));
        else
            imageStatus.setImageResource(StatusInfo.getGlobalStatusIcon(StatusInfo.STATUS_OFFLINE));

        imageXStatus.setImageResource(XStatusInfo.getIcon(p.xstatusIndex));
        imagePrivateStatus.setImageResource(StatusInfo.privateStatusIcons[p.privateStatus]);
    }
}
